package com.zjuee.web.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjuee.web.auth.mapper.RoleMenuMapper;
import com.zjuee.base.bean.response.CommonResultCode;
import com.zjuee.base.dto.common.auth.RoleMenuDto;
import com.zjuee.base.exception.BaseException;
import com.zjuee.base.exception.ServiceException;
import com.zjuee.base.model.common.auth.Role;
import com.zjuee.base.model.common.auth.RoleMenu;
import com.zjuee.service.auth.service.RoleMenuService;
import com.zjuee.service.auth.service.RoleService;
import com.zjuee.service.auth.vo.RoleMenuVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author wu liang
 * @since 1.0
 */
@Slf4j
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private RoleService roleService;

//    @Resource
//    private LoginDto loginDto;

    @Override
    public Boolean deleteByRoleId(Long roleId) {
        RoleMenuDto roleMenuDto = new RoleMenuDto();
        roleMenuDto.setRoleId(roleId);
        return roleMenuMapper.delete(fuzzyQuery(roleMenuDto)) > 0;

//        RoleMenu roleMenu = roleMenuMapper.selectById(id);
//        if (null == roleMenu) {
//            throw new ServiceException("The mapping does not exist in the mapping table");
//        }
//        return roleMenuMapper.deleteById(id) > 0;
    }


    @Override
    @Transactional
    public Boolean update(RoleMenuVo roleMenuVo) {
        Set<String> menus = new HashSet<String>(Arrays.asList(roleMenuVo.getMenuIds().split(",")));
        //查询角色是否为该组织
        Role existRole = roleService.selectById(roleMenuVo.getRoleId(), 0L);
        if (existRole==null) {
            throw new BaseException(CommonResultCode.CONSUMER_ERR, "角色不存在");
        }
        //删除角色权限
        deleteByRoleId(roleMenuVo.getRoleId());
        //添加新提交的资源id - 整理成List
        List<RoleMenu> roleMenuList = new ArrayList<>();
        for (String menuId : menus) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleMenuVo.getRoleId());
            roleMenu.setMenuId(Long.valueOf(menuId));
            roleMenuList.add(roleMenu);
        }
        return this.saveBatch(roleMenuList);
    }

    @Override
    public Long add(RoleMenu roleMenu) {
        RoleMenu select = selectByRMId(roleMenu.getRoleId(), roleMenu.getMenuId());
        Optional.ofNullable(select).ifPresent(id -> {
            throw new ServiceException("The mapping already exists in the mapping table");
        });
        if (roleMenuMapper.insert(roleMenu) > 0) {
            return roleMenu.getId();
        }
        throw new ServiceException("The mapping add to the mapping table failed");
    }

//    @Override
//    @Caching(
//            evict = {
//                    @CacheEvict(value = Common.Cache.ROLE_MENU + Common.Cache.ID, key = "#id", condition = "#result==true"),
//                    @CacheEvict(value = Common.Cache.ROLE_MENU + Common.Cache.GROUP_NAME, allEntries = true, condition = "#result==true"),
//                    @CacheEvict(value = Common.Cache.ROLE_MENU + Common.Cache.LIST, allEntries = true, condition = "#result==true")
//            }
//    )
//    public boolean delete(Long id) {
//        RoleMenu roleMenu = selectById(id);
//        if (null == roleMenu) {
//            throw new ServiceException("The mapping does not exist in the mapping table");
//        }
//        return roleMenuMapper.deleteById(id) > 0;
//    }

    //    @Override
//    public RoleMenu update(RoleMenu type) {
//        return null;
//    }
//
//    @Override
//    @Cacheable(value = Common.Cache.ROLE_MENU + Common.Cache.ID, key = "#id", unless = "#result==null")
//    public RoleMenu selectById(Long id) {
//        return roleMenuMapper.selectById(id);
//    }
//
//    @Override
//    public Page<RoleMenu> list(RoleMenuDto dto) {
//        return null;
//    }
//
//    @Override
    public LambdaQueryWrapper<RoleMenu> fuzzyQuery(RoleMenuDto roleMenuDto) {
        LambdaQueryWrapper<RoleMenu> queryWrapper = Wrappers.<RoleMenu>query().lambda();
        Optional.ofNullable(roleMenuDto).ifPresent(dto -> {
            if (dto.getRoleId() > 0L) {
                queryWrapper.eq(RoleMenu::getRoleId, dto.getRoleId());
            }
        });
        return queryWrapper;
    }


    public RoleMenu selectByRMId(Long roleId, Long menuId) {
        String key = roleId + "" + menuId;
        LambdaQueryWrapper<RoleMenu> queryWrapper = Wrappers.<RoleMenu>query().lambda()
                .eq(RoleMenu::getRoleId, roleId).eq(RoleMenu::getMenuId, menuId);
        return roleMenuMapper.selectOne(queryWrapper);
    }
}
